package com.pth.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.pth.dao.MessageDAO;
import com.pth.model.Message;

public class MessageDAOImpl implements MessageDAO {

	private HibernateTemplate hibernateTemplate;
	
	public void save(Message message) {

		hibernateTemplate.save(message);
		
	}

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	
	@SuppressWarnings("unchecked")
	public List<Message> getAllMessages(final int pagesize,final int offset) {


		final String hqlString="from Message  order by mpublishtime desc";
		
		List<Message> list=hibernateTemplate.executeFind(new HibernateCallback() {

			public Object doInHibernate(Session arg0) throws HibernateException,
					SQLException {

				return arg0.createQuery(hqlString).setFirstResult(offset).setMaxResults(pagesize).list();
				
			}
		});
		
		return list;
		
		
		
	}

	public int getAllNum() {

		
		return hibernateTemplate.find("from Message").size();
	}

	public Message getMessageByid(int id) {


		return hibernateTemplate.get(Message.class, id);
		
	}

}
